package MyThread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: AliceMana
 * Date: 2023-01-02
 * Time: 16:23
 */

// 懒汉模式
class SingletonLazy {

    // 此 volatile 解决两个问题
    // 1. 解决内存可见性问题
    // 2. 解决编译器优化的指令重排序问题
    private volatile static SingletonLazy instance = null;

    public static SingletonLazy getInstance() {
        // 判定是否要加锁
        if (instance == null) {
            synchronized (SingletonLazy.class) {
                // 判定是否要创建对象
                if (instance == null) {
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }

    private SingletonLazy() {}
}

public class ThreadDemo20 {
    public static void main(String[] args) {
        SingletonLazy s1 = SingletonLazy.getInstance();
        SingletonLazy s2 = SingletonLazy.getInstance();
        System.out.println(s1 == s2);
    }
}
